package cn.singno.bob.web.security;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * CSRF校验拦截器，这里只过滤POST请求
 * @author 鲍建明
 *
 */
public class CsrfInterceptor extends HandlerInterceptorAdapter {

	private String loginUrl = "/login.jsp";					//


	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		
		if( "POST".equalsIgnoreCase(request.getMethod()) ){
			String csrfToken = CsrfTokenManager.getTokenFromRequest(request);
			String oldToken = getToken(request);
			if( StringUtils.isBlank(csrfToken) || !StringUtils.equals(csrfToken, oldToken) ){
				response.sendRedirect(loginUrl);
				return false;
			}
		}
		return true;
	}
	
	/**
	 * 获取Session中的token
	 * @param request
	 * @return
	 */
	private String getToken(HttpServletRequest request){
		/*if(this.CacheManager == null){
			return (String) request.getSession().getAttribute(CsrfTokenManager.CSRF_PARAM_NAME);
		}else{
			return this.CacheManager.getCache(cacheName).get(CsrfTokenManager.CSRF_PARAM_NAME, String.class);
		}*/
		return (String) request.getSession().getAttribute(CsrfTokenManager.CSRF_TOKEN_FOR_SESSION_ATTR_NAME);
	}
	
	/**
	 * 获取当前的URL
	 * @param request
	 * @return
	 */
	private String getCurrentUrl(HttpServletRequest request){
		String currentUrl = request.getRequestURL().toString();
		if( !StringUtils.isEmpty(request.getQueryString()) ){
			currentUrl += "?" + request.getQueryString();
		}
		return currentUrl;
	}
	
	
	/**
	 * 
	 * <p>描述：</p>
	 * <pre>
	 * 	如果token不正确时，重定向到登录页面   
	 * </pre>
	 * @param loginUrl
	 */
	public void setLoginUrl(String loginUrl) {
		this.loginUrl = loginUrl;
	}

	public String getLoginUrl() {
		return loginUrl;
	}
}
